<template>
  <view class="register-container">
    <view class="register-header">
      <text class="title">注册账号</text>
      <text class="subtitle">欢迎加入我们</text>
    </view>

    <view class="register-form">
      <uni-forms ref="registerForm" :modelValue="formData" :rules="rules">
        <uni-forms-item name="username">
          <uni-easyinput
            v-model="formData.username"
            placeholder="请输入用户名（4-20位字母数字）"
            :clearable="true"
          ></uni-easyinput>
        </uni-forms-item>
        
        <uni-forms-item name="password">
          <uni-easyinput
            v-model="formData.password"
            type="password"
            placeholder="请输入密码（6-20位）"
            :clearable="true"
          ></uni-easyinput>
        </uni-forms-item>
        
        <uni-forms-item name="confirmPassword">
          <uni-easyinput
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认密码"
            :clearable="true"
          ></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="phone">
          <uni-easyinput
            v-model="formData.phone"
          placeholder="请输入手机号"
            :clearable="true"
          ></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="verifyCode">
          <view class="verify-code-input">
            <uni-easyinput
              v-model="formData.verifyCode"
          placeholder="请输入验证码"
              :clearable="true"
            ></uni-easyinput>
        <button 
              class="send-code-btn" 
              :disabled="countdown > 0"
          @click="handleSendCode"
        >
              {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
        </button>
      </view>
        </uni-forms-item>
      </uni-forms>

      <view class="agreement">
        <checkbox
          :checked="formData.agreement" 
          @tap="formData.agreement = !formData.agreement"
          color="#ff5500"
        />
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @click="showAgreement">《用户协议》</text>
          和
          <text class="link" @click="showPrivacy">《隐私政策》</text>
        </text>
      </view>

      <button 
        class="register-btn" 
        @click="handleRegister" 
        :loading="loading"
      >注 册</button>

      <view class="login-link">
        已有账号？
        <text @click="navigateTo('/pages/user/auth/login')">去登录</text>
    </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      countdown: 0,
      timer: null,
      formData: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        verifyCode: '',
        agreement: false
      },
      rules: {
        username: {
          rules: [{
            required: true,
            errorMessage: '请输入用户名'
          }, {
            pattern: /^[a-zA-Z0-9]{4,20}$/,
            errorMessage: '用户名必须是4-20位字母或数字'
          }]
        },
        password: {
          rules: [{
            required: true,
            errorMessage: '请输入密码'
          }, {
            minLength: 6,
            maxLength: 20,
            errorMessage: '密码长度必须在6-20位之间'
          }]
        },
        confirmPassword: {
          rules: [{
            required: true,
            errorMessage: '请确认密码'
          }, {
            validateFunction: (rule, value, data) => {
              return value === data.password
            },
            errorMessage: '两次输入的密码不一致'
          }]
        },
        phone: {
          rules: [{
            required: true,
            errorMessage: '请输入手机号'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            errorMessage: '手机号格式不正确'
          }]
        },
        verifyCode: {
          rules: [{
            required: true,
            errorMessage: '请输入验证码'
          }, {
            pattern: /^\d{6}$/,
            errorMessage: '验证码必须是6位数字'
          }]
        }
      }
    }
  },
  methods: {
    navigateTo(url) {
      uni.navigateTo({ url })
    },
    showAgreement() {
      // 显示用户协议
      uni.navigateTo({
        url: '/pages/common/agreement'
      })
    },
    showPrivacy() {
      // 显示隐私政策
      uni.navigateTo({
        url: '/pages/common/privacy'
      })
    },
    startCountdown() {
        this.countdown = 60
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--
          } else {
            clearInterval(this.timer)
          }
        }, 1000)
    },
    async handleSendCode() {
      try {
        // 验证手机号
        await this.$refs.registerForm.validateField('phone')
        
        // 防止重复发送
        if (this.countdown > 0) return
        
        uni.showLoading({
          title: '发送中...',
          mask: true
        })
        
        // 发送验证码，type=1 表示注册验证码
        const res = await this.$api.user.auth.sendVerifyCode(this.formData.phone, 1)
        
        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
          
          // 开始倒计时
          this.startCountdown()
        } else {
          uni.showToast({
            title: res.message || '发送失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      }
    },
    async handleRegister() {
      try {
        // 表单验证
        const valid = await this.$refs.registerForm.validate()
        if (!valid) return

        // 检查用户协议
        if (!this.formData.agreement) {
          uni.showToast({
            title: '请先同意用户协议和隐私政策',
            icon: 'none'
          })
          return
        }

        this.loading = true
        uni.showLoading({
          title: '注册中...',
          mask: true
        })

        // 构造注册数据，与API定义保持一致
        const registerData = {
          username: this.formData.username,
          password: this.formData.password,
          confirmPassword: this.formData.confirmPassword,
          phone: this.formData.phone,
          verifyCode: this.formData.verifyCode
        }

        const res = await this.$api.user.auth.register(registerData)

        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })
          
          // 延迟跳转到登录页
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/user/auth/login'
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '注册失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('注册失败:', error)
        uni.showToast({
          title: error.message || '注册失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  padding: 40rpx;
  background-color: #ffffff;

  .register-header {
    margin: 60rpx 0;

    .title {
      font-size: 48rpx;
      color: #333;
      font-weight: bold;
    }

    .subtitle {
      font-size: 28rpx;
      color: #999;
      margin-top: 20rpx;
      display: block;
    }
  }

  .register-form {
    margin-top: 40rpx;

    .verify-code-input {
    display: flex;
    align-items: center;
      gap: 20rpx;

      :deep(.uni-easyinput) {
        flex: 1;
      }

      .send-code-btn {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        font-size: 24rpx;
        color: #ff5500;
        background-color: #fff;
        border: 1rpx solid #ff5500;
        border-radius: 35rpx;
        padding: 0;

        &:disabled {
          color: #999;
          border-color: #ddd;
          background-color: #f5f5f5;
        }
      }
    }

    .agreement {
      display: flex;
      align-items: center;
      margin: 40rpx 0;
      padding: 0 20rpx;

      .agreement-text {
        font-size: 24rpx;
        color: #666;
        margin-left: 10rpx;

        .link {
          color: #ff5500;
        }
      }
  }

  .register-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
      background-color: #ff5500;
    color: #ffffff;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin-top: 40rpx;

      &:active {
        opacity: 0.8;
      }
    }

    .login-link {
      text-align: center;
      margin-top: 40rpx;
      font-size: 28rpx;
      color: #666;

      text {
        color: #ff5500;
        margin-left: 10rpx;
      }
    }
  }
}
</style> 